import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'


import styles from '../../styles/Goods.module.scss'
import { useEffect, useRef, useState } from 'react'
import router from 'next/router'
import { BookService, RemarkService } from '../../services'
import { IBooks, Remark } from '../../models/types'
import { Badge, Ellipsis, ImageViewer, InfiniteScroll, Input, Mask, Popup, Swiper, Toast } from 'antd-mobile'
import timeConvert from '../../libs/timeConvert'
import { Warnicon, Winicon } from '../../components/Icon'
import { useRequest, useUpdateEffect } from 'ahooks'
import { Identity, Relevance } from '../../models/enums'
import { InputRef } from 'antd-mobile/es/components/input'
import Reamrk from '../../components/Remark'
import { judgeLoad, uniqueFunc } from '../../libs/utils'

interface Props {
  book: IBooks,
  remarks: Remark[]
  total: number
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const bookId = ctx.query.id as string
  const token = ctx.req.cookies.token
  const res = await BookService.detail(bookId, token)
  const remarkRes = await RemarkService.list(bookId, 0, 3, false, token)

  if (!res.data._id) return {
    redirect: {
      destination: '/default',
      permanent: false
    }
  }
  return {
    props: {
      book: res.data,
      remarks: remarkRes.data.list,
      total: remarkRes.data.total
    }
  }
}

const pageSize = 10

const Goods: NextPage<Props> = ({ book, remarks, total: startTotal }) => {

  const banners = book?.banner.map((item, index) => (
    <Swiper.Item key={index}
      onClick={e => {
        ImageViewer.Multi.show({
          images: book.banner,
          defaultIndex: index
        })
      }}
    >
      <div className={styles.banner}>
        <main style={{ backgroundImage: `url('${item}')` }} />
        <img src={item} alt="" />
      </div>
    </Swiper.Item>
  ))

  let [names, prices, stocks] = ['', '', '']

  book.books.forEach(item => {
    names = names + item.bookname + ' / '
    prices = prices + item.price + ' 元/ '
    stocks = stocks + item.stock + ' 本/'
  })
  const { major, updateAt, content, putaway } = book
  const { nickname, signature, qqnumber, role, _id: userId } = book.user
  const info = ['售价', '书名', '专业', '更新', '库存']
  const value = [prices, names,
    `${major[0]}${major[1] ? ',' + major[1] : ''}`,
    timeConvert(updateAt), stocks]

  const person = ['卖家', '签名', '联系号码']
  const pvalue = [nickname, signature, qqnumber]

  const [isCol, setCol] = useState(book?.colState)
  const [islike, setLike] = useState(book?.like)
  const [carNum, setCarNum] = useState(book?.carnum)
  const [note, setNote] = useState(true)
  const [remarking, setRemarking] = useState(false)
  const [isPop, setIspop] = useState(false)
  const [remarkPop, setRemarkPop] = useState(false)
  const [hasMore, setHasMore] = useState<boolean>(true)
  const refInput = useRef<InputRef>(null)
  const [remark, setRemark] = useState('')
  const [remarklist, setRemarklist] = useState<Remark[]>(remarks)
  const [indexs, setIndexs] = useState<number[]>([])
  const [total, setTotal] = useState<number>(startTotal)

  const { data, run: dealBook } = useRequest(
    BookService.dealBook,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          Toast.show({ content: <Winicon text={res.msg} /> })
          if (res.msg.includes('点赞')) {
            setLike(!islike)
          } else {
            setCol(!isCol)
          }
        } else Toast.show({ content: <Warnicon text={res.msg as string} /> })
      },
      debounceInterval: 500
    })

  const { data: Remarks, run: getRemark } = useRequest(
    RemarkService.list,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          const newList = res.data.list
          setRemarklist(oldList => {
            const arr = uniqueFunc([...oldList, ...newList]) as Remark[]
            setHasMore(arr.length < res.data.total)
            if (arr.length > 3) setRemarkPop(true)
            return arr
          })
          setTotal(res.data.total)
        } else setHasMore(false)
      },
      throttleInterval: 200
    }
  )

  async function getMore(bookId: string, skip: number, limit: number, flag: boolean) {
    getRemark(bookId, skip, limit, flag)
  }

  async function addRemark() {
    const str = remark.replace(/\s*/g, "")
    if (str.length < 5) Toast.show({ content: <Warnicon text='需要大于5个字' /> })
    else {
      const res = await RemarkService.add(book._id, remark, 0)
      if (res.stat === 'OK') {
        Toast.show({ content: <Winicon text={'发布成功'} /> })
        setRemark('')
        remarklist.unshift(res.data)
        setRemarklist(remarklist.map(v => v))
      }
      else Toast.show({ content: <Warnicon text={res.msg} /> })
    }
    setRemarking(false)
  }

  useEffect(() => {
    if (remarking) refInput.current?.focus()
  }, [remarking])

  const firstUpload = useRef(true)

  useUpdateEffect(() => {
    async function getDate() {
      const res = await RemarkService.list(book._id, 0, 3, !note)
      if (res.stat === 'OK') {
        setRemarklist(res.data.list)
        setTotal(res.data.total)
      }
    }
    if (firstUpload.current) {
      firstUpload.current = false
      return
    }
    getDate()
  }, [book._id, getRemark, note])

  return (
    <div className="page">
      <Head>
        <title>书籍详情页</title>
      </Head>
      <div className="wrapRaw">
        <i onClick={() => router.back()} className={styles.goback + ' iconfont icon-back_light'}></i>
        <Swiper indicatorProps={{
          style: {
            '--dot-color': 'rgba(0, 0, 0, 0.4)',
            '--active-dot-color': '#497749',
            '--dot-size': '8px',
            '--active-dot-size': '20px',
            '--dot-border-radius': '50%',
            '--active-dot-border-radius': '15px',
            '--dot-spacing': '8px',
          }
        }} loop >{banners}</Swiper>
        <div className={styles.info}>
          <div className={styles.header}>
            <h3>{book.title}</h3>
            {!isCol ? <i className={styles.collect + ' iconfont icon-shoucang'}
              onClick={() => dealBook(book._id, Relevance.Collect, true)}></i>
              : <i className={styles.collected + ' iconfont icon-shoucang1'}
                onClick={() => dealBook(book._id, Relevance.Collect, false)}></i>}
          </div>
          {
            info.map((item, idx) => (
              <li key={idx}>
                <span className={styles.key}>{item}</span>
                <p>:</p>
                <span className={styles.value}>
                  <Ellipsis direction='end' content={value[idx] as string} />
                </span>
              </li>
            ))
          }
          <div className={styles.seller}>
            <div className={styles.person}>
              {
                person.map((item, idx) => (
                  <li key={idx}>
                    <span className={styles.key}>{item}</span>
                    <p>:</p>
                    <span className={styles.value}>
                      <Ellipsis direction='end' content={pvalue[idx] as string} />
                    </span>
                  </li>
                ))
              }
            </div>
            <img
              src={book.user.avatar} alt=""
              onClick={() => router.push('/user/' + book.user._id + '/dynamic')}
            />
          </div>
        </div>
        <div className={styles.tag}>
          <div>
            <span>
              浏览量 {book.views}次
            </span>
            {!islike ? <i className={' iconfont icon-dianzan'}
              onClick={() => dealBook(book._id, Relevance.Mythumb, true)}></i>
              : <i className={styles.thued + ' iconfont icon-hanhan-01-01'}
                onClick={() => dealBook(book._id, Relevance.Mythumb, false)}></i>}
          </div>
          <ul>
            {role === Identity.Official && <li className={styles.tagItem}>
              <span>自营</span>
              <p>正版 · 干净卫生 · 当天发货</p>
              <img src="" alt="" />
            </li>}
            <li className={styles.tagItem}>
              <span>环保</span>
              <p>了解民大的环保探索</p>
              <img src="" alt="" />
            </li>
          </ul>
        </div>
        <div className={styles.brief}>
          <h2>简介和目录</h2>
          <article>{content}</article>
        </div>
        <div className={styles.remark}>
          <header>
            <li
              onClick={() => setNote(true)}
              className={note ? styles.active : ''}>
              留言 {note ? total : ''}
            </li>
            <li
              onClick={() => setNote(false)}
              className={note ? '' : styles.active}>
              评价 {note ? '' : total}
            </li>
          </header>
          <div className={styles.input}>
            {book.logAvatar && <img src={book.logAvatar} alt="头像" className="avatar" />}
            <span onClick={() => {
              if (note) setRemarking(true)
            }}>
              {note ? '留言提问关于商品的问题' : '购买后者可以参与评价~'}
            </span>
          </div>
          {remarklist.map((item, i) => {
            if (i < 3) return (
              <div key={item._id} >
                <Reamrk remark={item} isMai={item.user._id === userId} />
              </div>
            )
          })}
          {total > 3 && <div
            onClick={async () => {
              await getRemark(book._id, 0, pageSize, !note)
            }}
            className={styles.express}>
            <span>查看全部{note ? '留言' : '评价'}</span>
            <i className=' iconfont icon-xiangyou1' />
          </div>}
        </div>

        <div className="relate">
          {/* <h4>相关推荐</h4> */}
        </div>
      </div>
      {remarking ? <div className={styles.bottomInput}>
        <div className="admInput">
          <Input
            value={remark}
            ref={refInput}
            placeholder={note ? '留言提问关于商品的问题' : '购买后者可以参与评价~'}
            onChange={v => setRemark(v)}
            onEnterPress={async () => await addRemark()}
          />
        </div>
        <button onClick={async () => await addRemark()}>发送</button>
      </div> : <div className={styles.bottom}>
        <Link href={"/"} passHref>
          <li className='iconfont icon-zhuye1'></li>
        </Link>
        <Badge color='#c75943' content={carNum > 0 ? carNum : null}
          style={{ '--top': '10%' }}
        >
          <Link href={"/cart"} passHref>
            <li className='iconfont icon-shouye'></li>
          </Link>
        </Badge>
        <button disabled={!putaway} onClick={() => setIspop(true)}>加入购物车</button>
      </div>
      }
      <Mask
        className={styles.mask}
        visible={remarking}
        onMaskClick={() => setRemarking(false)}
        opacity={0}
      />
      <Popup
        visible={isPop}
        onMaskClick={() => setIspop(false)}
        bodyStyle={{ height: '60vh' }}
      >
        <div className={styles.xiadan}>
          <h4>具体下单</h4>
          {
            book.books.map((item, idx) => (
              <div
                onClick={() => {
                  if (indexs.includes(idx)) {
                    const i = indexs.indexOf(idx)
                    indexs.splice(i, 1)
                    setIndexs(indexs.map(v => v))
                  } else {
                    if (item.stock === 0) return
                    indexs.push(idx)
                    setIndexs(indexs.map(v => v))
                  }
                }}
                key={idx}
                className={indexs.includes(idx) ? styles.select : ''}>
                <span>书名:{item.bookname}</span>
                <span>价格:{item.price}元</span>
                <span>余{item.stock}本</span>
              </div>
            ))
          }
          <button
            disabled={indexs.length === 0 || !putaway}
            onClick={async () => {
              const res = await BookService.dealcar(book._id, true, indexs)
              if (res.stat === 'OK') {
                Toast.show({ content: <Winicon text={res.msg} /> })
                setCarNum(carNum + 1)
                setIspop(false)
              }
              else Toast.show({ content: <Warnicon text={res.msg} /> })
            }}>加入购物车</button>
        </div>
      </Popup>
      <Popup
        visible={remarkPop}
        onMaskClick={() => setRemarkPop(false)}
        bodyStyle={{
          height: '80vh',
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px'
        }}
      >
        <div className={styles.liuyanPop}>
          <h3>{note ? '留言' : '评价'} · {total}</h3>
          <main>
            {remarklist.map(item => (
              <div key={item._id} >
                <Reamrk remark={item} isMai={item.user._id === userId} />
              </div>
            ))}
            {
              !judgeLoad(remarklist, hasMore) &&
              <InfiniteScroll
                loadMore={() => getMore(book._id, remarklist.length, pageSize, !note)}
                hasMore={hasMore}
              />
            }
          </main>
        </div>
      </Popup>
    </div>
  )
}

export default Goods
